<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.doctorRealName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="searchForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddDoctor">新增医生</el-button>
    </div>

    <!-- 医生表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="doctorId" label="医生ID" width="80" />
      <el-table-column prop="doctorRealName" label="医生姓名" />
      <el-table-column prop="title" label="职称" />
      <el-table-column prop="departmentId" label="所属科室">
        <template #default="scope">
          {{ scope.row.departmentVo.name }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="gender" label="性别" :formatter="formatGender" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditDoctor(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteDoctor(scope.row.doctorId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑医生对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="45%">
      <el-form :model="currentForm" :rules="rules" ref="doctorFormRef">
        <el-form-item label="医生姓名" prop="doctorRealName">
          <el-input v-model="currentForm.doctorRealName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="currentForm.password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="currentForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentForm.gender" placeholder="请选择性别">
            <el-option :value="0" label="男" />
            <el-option :value="1" label="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="currentForm.title" placeholder="请输入职称" />
        </el-form-item>
        <el-form-item label="所属科室" prop="departmentId">
          <!-- （实际项目中应替换为科室下拉选择框，需先获取科室列表） -->
          <el-select v-model="currentForm.departmentId" placeholder="请选择科室">
            <el-option v-for="item in departmentList" :key="item.departmentId" :label="item.name" :value="item.departmentId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {doctorDeleteOne, doctorInsertOne, doctorSelectPage, doctorUpdateOne} from "@/api/doctor.js";
import {departmentSelectPage} from "@/api/department.js";

// 表格数据
const tableData = ref([]);
const departmentList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索条件
const searchForm = reactive({
  doctorRealName: '',
  phone: '',
});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  doctorId: 0,
  username: '',
  password: '',
  departmentId: null,
  doctorRealName: '',
  email: '',
  phone: '',
  avatar: '',
  gender: null,
  title: '',
});
const doctorFormRef = ref(null);

// 验证规则
const rules = {
  doctorRealName: [{ required: true, message: '医生姓名不能为空', trigger: 'blur' }],
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '邮箱格式错误', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '电话格式错误', trigger: 'blur' },
  ],
  title: [{ required: true, message: '职称不能为空', trigger: 'blur' }],
  departmentId: [{ required: true, message: '科室不能为空', trigger: 'blur' }],
};

// 获取医生列表
const fetchDoctors = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      doctorRealName: searchForm.doctorRealName,
      phone: searchForm.phone,
    };
    if (params.doctorRealName === '') {
      delete params.doctorRealName;
    }
    if (params.phone === '') {
      delete params.phone;
    }
    const response = await doctorSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    console.log(error)
    ElMessage.error('获取医生列表失败');
  }
};

// 新增医生
const handleAddDoctor = () => {
  dialogTitle.value = '新增医生';
  dialogVisible.value = true;
  resetForm();
  fetchDepartmentList();
};

// 获取科室列表
const fetchDepartmentList = async () => {
  try {
    const response = await departmentSelectPage({page: 1, size: 10000});
    departmentList.value = response.data.records;
  } catch (error) {
    console.log(error)
    ElMessage.error('获取科室列表失败');
  }
};

// 编辑医生
const handleEditDoctor = (row) => {
  dialogTitle.value = '编辑医生';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
  currentForm.departmentId = row.departmentVo.departmentId;
  fetchDepartmentList();
};

// 删除医生
const handleDeleteDoctor = (doctorId) => {
  ElMessageBox.confirm('确认删除该医生?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await doctorDeleteOne(doctorId)
      ElMessage.success('删除成功');
      await fetchDoctors();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存医生（新增/编辑）
const handleSubmit = () => {
  doctorFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.doctorId) {
          // 编辑
          await doctorUpdateOne(currentForm)
        } else {
          // 新增
          await doctorInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchDoctors();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchDoctors();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchDoctors();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchDoctors();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  Object.assign(searchForm, {
    doctorRealName: '',
    phone: '',
  });
  fetchDoctors();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    doctorId: 0,
    departmentId: null,
    username: '',
    password: '',
    doctorRealName: '',
    email: '',
    phone: '',
    avatar: '',
    gender: null,
    title: '',
  });
  doctorFormRef.value?.clearValidate();
};

// 格式化性别
const formatGender = (row) => {
  return row.gender === 0 ? '男' : '女';
};

// 初始化数据
onMounted(() => {
  fetchDoctors();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}
.action-bar {
  margin-bottom: 15px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
